package org.osami.gateway.mediator.drools;

import java.util.Iterator;
import java.util.List;

import org.osami.gateway.sensor.SenseData;
import org.osami.gateway.type.Temperature;
import org.ow2.jasmine.rules.api.IDroolsWorkingMemory;
import org.ow2.jasmine.rules.api.IDroolsWorkingMemoryPool;

import fr.liglab.adele.cilia.Data;
import fr.liglab.adele.cilia.framework.IProcessor;

public class MediatorDrools implements IProcessor {

    private static final String GATEWAY_ID = "totolagatewaymagique";

    private static final String DEFAULT_UNIT = "celsius";

    private final String DEFAULT_MEMORY_NAME = "default";

    private IDroolsWorkingMemory droolmem;

    /**
     * Add the Temperature object to the drools working memory.
     */
    public List process(List dataset) {
        Temperature temperature = null;

        Iterator i = dataset.iterator();

        SenseData sensedata;
        double average = 0;
        // Get the data
        // TODO check the unit and convert if needed
        while (i.hasNext()) {
            Data data = (Data) i.next();
            sensedata = (SenseData) data.getContent();
            average += sensedata.getValue();
        }

        average /= Double.valueOf(dataset.size());
        temperature = new TemperatureImpl(GATEWAY_ID, average, DEFAULT_UNIT);

        // Add the Temperature average to the Drools memory
        droolmem.insert(temperature);

        return dataset;
    }

    private void bindDroolsMemoryPool(IDroolsWorkingMemoryPool pool) {
        droolmem = pool.get(DEFAULT_MEMORY_NAME);

        if (droolmem == null) {
            throw new RuntimeException("The DroolsWorkingMemory " + DEFAULT_MEMORY_NAME + "cannot be found ! mediator down ");
        }
    }

    private void stop() {
        droolmem = null;
    }

    private class TemperatureImpl implements Temperature {

        private String gwid;

        private double val;

        private String unit;

        private long stamp;

        public TemperatureImpl(String pGatewayId, double pValue, String pUnit) {
            unit = pUnit;
            gwid = pGatewayId;
            val = pValue;
            stamp = System.currentTimeMillis();
        }

        public String getGatewayId() {
            return gwid;
        }

        public double getTemperature() {
            return val;
        }

        public long getTimeStamp() {
            return stamp;
        }

        public String getUnit() {
            return unit;
        }
    }

}
